import axios from 'axios'
import type { 
  WorkflowDefinition, 
  WorkflowInstance, 
  WorkflowTask, 
  User, 
  Department, 
  Role,
  WorkflowStep,
  ApiResponse,
  CreateWorkflowRequest,
  StartWorkflowRequest,
  ApproveTaskRequest
} from '../types/workflow'

const API_BASE_URL = 'http://localhost:5000/api'

// 创建axios实例
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
apiClient.interceptors.request.use(
  (config) => {
    // 可以在这里添加认证token
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
apiClient.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    console.error('API请求失败:', error)
    return Promise.reject(error)
  }
)

// 工作流定义API
export const createWorkflowDefinition = async (data: CreateWorkflowRequest): Promise<ApiResponse<WorkflowDefinition>> => {
  try {
    const response = await apiClient.post('/api/workflow/definitions', data)
    return response.data
  } catch (error: any) {
    console.error('创建工作流定义失败:', error)
    throw error
  }
}

export const getWorkflowDefinitions = async (): Promise<ApiResponse<WorkflowDefinition[]>> => {
  try {
    const response = await apiClient.get('/api/workflow/definitions')
    return response.data
  } catch (error: any) {
    console.error('获取工作流定义失败:', error)
    throw error
  }
}

export const getWorkflowDefinition = async (id: string): Promise<ApiResponse<WorkflowDefinition>> => {
  try {
    const response = await apiClient.get(`/api/workflow/definitions/${id}`)
    return response.data
  } catch (error: any) {
    console.error('获取工作流定义失败:', error)
    throw error
  }
}

export const updateWorkflowDefinition = async (id: string, data: CreateWorkflowRequest): Promise<ApiResponse<WorkflowDefinition>> => {
  try {
    const response = await apiClient.put(`/api/workflow/definitions/${id}`, data)
    return response.data
  } catch (error: any) {
    console.error('更新工作流定义失败:', error)
    throw error
  }
}

export const deleteWorkflowDefinition = async (id: string): Promise<ApiResponse<void>> => {
  try {
    const response = await apiClient.delete(`/api/workflow/definitions/${id}`)
    return response.data
  } catch (error: any) {
    console.error('删除工作流定义失败:', error)
    throw error
  }
}

// 工作流实例API
export const startWorkflow = async (data: StartWorkflowRequest): Promise<ApiResponse<WorkflowInstance>> => {
  try {
    const response = await apiClient.post('/api/workflow/instances', data)
    return response.data
  } catch (error: any) {
    console.error('启动工作流失败:', error)
    throw error
  }
}

export const getWorkflowInstances = async (): Promise<ApiResponse<WorkflowInstance[]>> => {
  try {
    const response = await apiClient.get('/api/workflow/instances')
    return response.data
  } catch (error: any) {
    console.error('获取工作流实例失败:', error)
    throw error
  }
}

export const getWorkflowInstance = async (id: string): Promise<ApiResponse<WorkflowInstance>> => {
  try {
    const response = await apiClient.get(`/api/workflow/instances/${id}`)
    return response.data
  } catch (error: any) {
    console.error('获取工作流实例失败:', error)
    throw error
  }
}

export const suspendWorkflow = async (id: string): Promise<ApiResponse<void>> => {
  try {
    const response = await apiClient.post(`/api/workflow/instances/${id}/suspend`)
    return response.data
  } catch (error: any) {
    console.error('暂停工作流失败:', error)
    throw error
  }
}

export const resumeWorkflow = async (id: string): Promise<ApiResponse<void>> => {
  try {
    const response = await apiClient.post(`/api/workflow/instances/${id}/resume`)
    return response.data
  } catch (error: any) {
    console.error('恢复工作流失败:', error)
    throw error
  }
}

// 工作流任务API
export const getTasks = async (assignee?: string, status?: string): Promise<ApiResponse<WorkflowTask[]>> => {
  try {
    const params = new URLSearchParams()
    if (assignee) params.append('assignee', assignee)
    if (status) params.append('status', status)
    
    const response = await apiClient.get(`/api/workflow/tasks?${params.toString()}`)
    return response.data
  } catch (error: any) {
    console.error('获取任务失败:', error)
    throw error
  }
}

export const approveTask = async (taskId: string, data: ApproveTaskRequest): Promise<ApiResponse<WorkflowTask>> => {
  try {
    const response = await apiClient.post(`/api/workflow/tasks/${taskId}/approve`, data)
    return response.data
  } catch (error: any) {
    console.error('审批任务失败:', error)
    throw error
  }
}

// 用户和组织API
export const getUsers = async (): Promise<ApiResponse<User[]>> => {
  try {
    const response = await apiClient.get('/api/workflow/users')
    return response.data
  } catch (error: any) {
    console.error('获取用户列表失败:', error)
    throw error
  }
}

export const getDepartments = async (): Promise<ApiResponse<Department[]>> => {
  try {
    const response = await apiClient.get('/api/workflow/departments')
    return response.data
  } catch (error: any) {
    console.error('获取部门列表失败:', error)
    throw error
  }
}

export const getRoles = async (): Promise<ApiResponse<Role[]>> => {
  try {
    const response = await apiClient.get('/api/workflow/roles')
    return response.data
  } catch (error: any) {
    console.error('获取角色列表失败:', error)
    throw error
  }
}

// 高级工作流步骤API
export const createParallelStep = async (data: any): Promise<ApiResponse<WorkflowStep>> => {
  try {
    const response = await apiClient.post('/api/workflow/steps/parallel', data)
    return response.data
  } catch (error: any) {
    console.error('创建并行步骤失败:', error)
    throw error
  }
}

export const createScriptStep = async (data: any): Promise<ApiResponse<WorkflowStep>> => {
  try {
    const response = await apiClient.post('/api/workflow/steps/script', data)
    return response.data
  } catch (error: any) {
    console.error('创建脚本步骤失败:', error)
    throw error
  }
}

export const createEmailStep = async (data: any): Promise<ApiResponse<WorkflowStep>> => {
  try {
    const response = await apiClient.post('/api/workflow/steps/email', data)
    return response.data
  } catch (error: any) {
    console.error('创建邮件步骤失败:', error)
    throw error
  }
}

export const createTimerStep = async (data: any): Promise<ApiResponse<WorkflowStep>> => {
  try {
    const response = await apiClient.post('/api/workflow/steps/timer', data)
    return response.data
  } catch (error: any) {
    console.error('创建定时器步骤失败:', error)
    throw error
  }
}

export const createWaitStep = async (data: any): Promise<ApiResponse<WorkflowStep>> => {
  try {
    const response = await apiClient.post('/api/workflow/steps/wait', data)
    return response.data
  } catch (error: any) {
    console.error('创建等待步骤失败:', error)
    throw error
  }
}

export const createWebhookStep = async (data: any): Promise<ApiResponse<WorkflowStep>> => {
  try {
    const response = await apiClient.post('/api/workflow/steps/webhook', data)
    return response.data
  } catch (error: any) {
    console.error('创建Webhook步骤失败:', error)
    throw error
  }
}

export const createNotificationStep = async (data: any): Promise<ApiResponse<WorkflowStep>> => {
  try {
    const response = await apiClient.post('/api/workflow/steps/notification', data)
    return response.data
  } catch (error: any) {
    console.error('创建通知步骤失败:', error)
    throw error
  }
}

export const createSubprocessStep = async (data: any): Promise<ApiResponse<WorkflowStep>> => {
  try {
    const response = await apiClient.post('/api/workflow/steps/subprocess', data)
    return response.data
  } catch (error: any) {
    console.error('创建子流程步骤失败:', error)
    throw error
  }
}

// 默认导出
const WorkflowApiService = {
  // 工作流定义管理
  createWorkflowDefinition,
  getWorkflowDefinitions,
  getWorkflowDefinition,
  updateWorkflowDefinition,
  deleteWorkflowDefinition,
  
  // 工作流实例管理
  startWorkflow,
  getWorkflowInstances,
  getWorkflowInstance,
  suspendWorkflow,
  resumeWorkflow,
  
  // 任务管理
  getTasks,
  approveTask,
  
  // 用户和组织管理
  getUsers,
  getDepartments,
  getRoles,

  // 高级工作流步骤API
  createParallelStep,
  createScriptStep,
  createEmailStep,
  createTimerStep,
  createWaitStep,
  createWebhookStep,
  createNotificationStep,
  createSubprocessStep
}

export default WorkflowApiService 